import {useEffect, useState} from 'react'
import {bitable} from "@lark-base-open/js-sdk";
import {Button} from "@douyinfe/semi-ui";



function RowToJSON() {
    const [rows,setRows] = useState([])


    async function getRows() {
        let rows:any = []
        let table = await bitable.base.getActiveTable()
        let view = await table.getActiveView()
        let visibleFields = await view.getVisibleFieldIdList()
        let visibleRecordIds = await view.getVisibleRecordIdList()

        console.log(view)
        let fieldIdNameMap:any = {}
        let fieldNameIdMap:any = {}
        let fields = await table.getFieldMetaList()
        for (let field of fields) {
            fieldIdNameMap[field.id] = field.name
            fieldNameIdMap[field.name] = field.id
        }
        let recordInfo = await table.getRecords({
            viewId:view.id
        })
        let records = recordInfo.records
        for (let record of records) {
            if (!visibleRecordIds.includes(record.recordId)) continue
            let row:any = {}
            let fields = record.fields
            for (let [key,value] of Object.entries(fields)) {
                if (!visibleFields.includes(key)) continue
                if (!value) continue
                let name = fieldIdNameMap[key]
                if (value && Array.isArray(value)){
                    // @ts-ignore
                    value = value.map(item=>item.text).join("")
                }
                // @ts-ignore
                if (value && value.text){
                    // @ts-ignore
                    value = value.text
                }
                row[name] = value
            }
            // 全null 的不要
            if (!Object.values(row).some(item=>item)){
                continue
            }
            rows.push(row)
        }
        setRows(rows)
    }
    useEffect(()=>{
        getRows()
    },[])

    return <>
        <Button onClick={getRows}> 获取json</Button>
        <pre>
            {JSON.stringify(rows,null,4)}
        </pre>
    </>
}


function App() {
  return (
    <>
      <RowToJSON></RowToJSON>
    </>
  )
}

export default App
